package cn.gailvlun.gll.presentation.xroom

import android.arch.lifecycle.ViewModelProviders
import android.databinding.DataBindingUtil
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.gailvlun.gll.R
import cn.gailvlun.gll.bean.PlaceHolder
import cn.gailvlun.gll.chatlib.event.CrossMatchSuccessEvent
import cn.gailvlun.gll.chatlib.event.CrossStatus
import cn.gailvlun.gll.chatlib.event.CrossStatusEvent
import cn.gailvlun.gll.databinding.FragmentCrossRoomMatchBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.presentation.base.BaseFragment
import cn.gailvlun.gll.presentation.xroom.vm.CrossRoomGameInfoViewModel
import cn.gailvlun.gll.util.*
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

class CrossRoomMatchFragment: BaseFragment() {
    override fun createHandler() {

    }

    private var toastTimer: Timer? = null
    private var mViewModel: CrossRoomGameInfoViewModel? = null

    private lateinit var mBinding: FragmentCrossRoomMatchBinding


    override fun initComponent(inflater: LayoutInflater, container: ViewGroup?): View {
        EventBus.getDefault().register(this)

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cross_room_match, container, false)

        mViewModel = ViewModelProviders.of(activity).get(CrossRoomGameInfoViewModel::class.java)

        toastTimer = Timer()
        toastTimer?.schedule(object: TimerTask() {
            override fun run() {
                ToastUtil.showShort("见习生们都太抢手了～\n" +
                        "你可以等会再来试试～")
            }
        }, 10000)

        return mBinding.root
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.btnCancel.setOnClickListener {
            toastTimer?.cancel()

            HttpMethods.getCrossService().quitMatch(mViewModel?.startMatchRes?.id!!)
                    .compose(RxUtil.applyScheduler())
                    .compose(bindToLifecycle())
                    .subscribe(object: HttpSubscriber<PlaceHolder>() {
                        override fun onSuccess(response: PlaceHolder?) {
                            
                            ToastUtil.showShort("已退出匹配")
                            val ft = fragmentManager.beginTransaction()
                            ft.remove(this@CrossRoomMatchFragment)
                            ft.commit()
                        }

                        override fun onFailure(errMsg: String?, response: PlaceHolder?, code: Int) {
                            DialogUtil.showError(mContext, errMsg)
                        }

                    })
        }

        Glide.with(mContext)
                .load(R.drawable.img_cross_room_introduce)
                .into(object: SimpleTarget<Drawable>() {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                        mBinding.llBg.setBackgroundDrawable(resource)
                    }
                })

        Glide.with(mContext)
                .load(ProfileUtil.getProfile().avatar)
                .into(mBinding.rivMyHeader)
    }

    override fun loadData(savedInstanceState: Bundle?) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onMatchSuccessEvent(event: CrossMatchSuccessEvent) {
        mViewModel?.getCrossRoomInfo(event.id)

        val trans = fragmentManager.beginTransaction()
        trans.replace(R.id.match_container, CrossRoomMatchSuccessFragment())
        trans.commit()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onBackground(event: BackgroundEvent) {
        if (event.isEnterBackground) {
            HttpMethods.getCrossService().quitMatch(mViewModel?.startMatchRes?.id!!)
                    .compose(RxUtil.applyScheduler())
                    .subscribe(object: HttpSubscriber<PlaceHolder>() {
                        override fun onSuccess(response: PlaceHolder?) {
                            ToastUtil.showShort("已退出匹配")
                            val ft = fragmentManager.beginTransaction()
                            ft.remove(this@CrossRoomMatchFragment)
                            ft.commitAllowingStateLoss()
                        }

                        override fun onFailure(errMsg: String?, response: PlaceHolder?, code: Int) {
                        }

                    })
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onOpen(event: CrossStatusEvent) {
        if (event.status == CrossStatus.BEFORE_OPEN) {
            CrossRoomChatActivity.openActivity(mContext, event.oppositeId, event.gameId)
            activity.finish()
        }
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)

        toastTimer?.cancel()
        super.onDestroy()
    }

}